package com.tqfframe.rabbitmq.config;

import com.tqfframe.rabbitmq.constants.RabbitConstants;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 死性队列 交换机配置
 * @author: Qifeng Tang
 * @date: 2022/11/17 10:22
 * @Version 1.0
 **/
@Configuration
public class RabbitMqDeadConfig {

    // ----------------------------------------------正常业务队列----------------------------------------------
    //提供一个消息队列，绑定死性交换机 Queue
    @Bean
    public Queue deadQueuePerQueueTTL() {
        Map<String, Object> args = new HashMap<>(3);
        //消息过期后，进入到死信交换机
        args.put("x-dead-letter-exchange", RabbitConstants.DEAD_EXCHANGE);
        //消息过期后，进入到死信交换机的路由key
        args.put("x-dead-letter-routing-key", RabbitConstants.DEAD_ROUTINGKEY);
        //如果该消息队列的时间5分钟未消费，则自动进入死性队列
        args.put("x-message-ttl", 5000);
        return new Queue(RabbitConstants.DEAD_COMMON_QUEUE, true, false, false, args);
    }

    // 提供一个普通消息的交互机
    @Bean
    DirectExchange deadCommonExchange() {
        return new DirectExchange(RabbitConstants.DEAD_COMMON_EXCHANGE, true, false);
    }

    //普通交互机和队列绑定
    @Bean
    Binding deadCommonBinding() {
        return BindingBuilder.bind(deadQueuePerQueueTTL())
                .to(deadCommonExchange()).with(RabbitConstants.DEAD_COMMON_ROUTINGKEY);
    }

    // ----------------------------------------------死性队列----------------------------------------------
    //死性消息队列
    @Bean
    Queue deadProcessQueue() {
        return QueueBuilder.durable(RabbitConstants.DEAD_QUEUE)
                .build();
    }

    //创建死性交换机
    @Bean
    public DirectExchange deadExchange() {
        return new DirectExchange(RabbitConstants.DEAD_EXCHANGE);
    }

    // 死性交换机绑定队列
    @Bean
    public Binding dlxBinding() {
        return BindingBuilder.bind(deadProcessQueue())
                .to(deadExchange()).with(RabbitConstants.DEAD_ROUTINGKEY);
    }

}
